package com.alex.aichat.service;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;

import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import io.reactivex.Flowable;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;

@Service
public class ChatService {
    @Value("${aliQwen.api-key}")
    private String apiKey;

    /**
     * 支持上下文（多轮对话），并根据deepthinking开关切换模型
     * @param messages 上下文数组，每项Map: {role: "user"/"assistant", content: "..."}
     * @param deepthinking 是否开启深度思考
     * @param onDelta 回调，reasoning和reply
     */
    public void streamChat(List<Map<String, String>> messages, boolean deepthinking, BiConsumer<String, String> onDelta)
            throws NoApiKeyException, ApiException, InputRequiredException {
        Generation gen = new Generation();
        // 转为DashScope的Message对象
        List<Message> msgList = new ArrayList<>();
        for (Map<String, String> m : messages) {
            msgList.add(Message.builder().role(m.get("role")).content(m.get("content")).build());
        }
        String model = deepthinking ? "deepseek-r1" : "deepseek-v3";
        GenerationParam param = GenerationParam.builder()
                .apiKey(apiKey)
                .model(model)
                .messages(msgList)
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .incrementalOutput(true)
                .build();
        Flowable<GenerationResult> result = gen.streamCall(param);
        result.blockingForEach(message -> {
            String reasoning = message.getOutput().getChoices().get(0).getMessage().getReasoningContent();
            String reply = message.getOutput().getChoices().get(0).getMessage().getContent();
            onDelta.accept(reasoning, reply);
        });
    }
}